﻿using System;
using System.Reflection;

namespace _48_在运行阶段检索特性实例_特性
{
    class Program
    {
        static void Main(string[] args)
        {
            Test v = new Test { RawName = "k003d6ex915f" };

            //调用checkTest对以上Test实例进行RawName属性验证
            bool b = CheckTest(v, nameof(Test.RawName));
            if (b)
            {
                Console.WriteLine("验证通过");
            }
            else
            {
                Console.WriteLine("验证失败");
            }
        }
        static bool CheckTest(Test t,string property)
        {
            //获取类型信息
            Type type = t.GetType();
            //查找属性成员
            PropertyInfo prop = type.GetProperty(property, BindingFlags.Public | BindingFlags.Instance);
            if (prop==null)
            {
                return false;
            }

            //获取特性
            MyAttribute att = prop.GetCustomAttribute<MyAttribute>();

            //获取实例的属性值
            string value = prop.GetValue(t) as string;
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            if (value.Length>att.MaxLen)
            {
                return false;
            }
            return true;
        }
    }
    //声明一个特性类，并指定它只能应用于属性成员
    [AttributeUsage(AttributeTargets.Property)]
    public class MyAttribute : Attribute
    {
        public char StartChar { get; set; }
        public int MaxLen { get; set; }
    }
    //声明一个测试类，并把MyAttribut应用到RawName属性上
    public class Test
    {
        [My(StartChar ='k', MaxLen = 7)]
        public string RawName { get; set; }
    }

}
